package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.apis.article.IArticleClient;
import com.heima.apis.wemedia.IWeMediaClient;
import com.heima.common.constants.user.UserConstants;
import com.heima.common.exception.LeadNewsException;
import com.heima.model.article.pojo.ApAuthor;
import com.heima.model.common.dto.PageResponseResult;
import com.heima.model.common.dto.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dto.AuthDto;
import com.heima.model.user.pojo.ApUser;
import com.heima.model.user.pojo.ApUserRealName;
import com.heima.model.wemedia.pojo.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealNameMapper;
import com.heima.user.service.ApUserRealNameService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author Ronaldo
 * @date 2021/8/1
 */
@Service
@Transactional
@Slf4j
public class ApUserRealNameServiceImpl extends ServiceImpl<ApUserRealNameMapper, ApUserRealName> implements ApUserRealNameService {

    @Autowired
    private ApUserMapper apUserMapper;

    @Autowired
    private IArticleClient articleClient;

    @Autowired
    private IWeMediaClient weMediaClient;

    @Override
    public ResponseResult queryPage(AuthDto authDto) {

        //参数合法性处理
        authDto.checkParam();

        LambdaQueryWrapper<ApUserRealName> realNameLambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (Objects.nonNull(authDto.getStatus())) {
            realNameLambdaQueryWrapper.eq(ApUserRealName::getStatus, authDto.getStatus());
        }

        IPage<ApUserRealName> page = new Page<>(authDto.getPage(), authDto.getSize());
        page = this.page(page, realNameLambdaQueryWrapper);

        List<ApUserRealName> userRealNameList = page.getRecords();
        log.info("auth info list {}" + userRealNameList);
        PageResponseResult pageResponseResult = new PageResponseResult(authDto.getPage(), authDto.getSize(), (int) page.getTotal());
        pageResponseResult.setData(userRealNameList);

        return pageResponseResult;
    }

    @GlobalTransactional
    @Override
    public ResponseResult examine(AuthDto authDto, Short status) {

        //参数判断
        if (Objects.isNull(authDto.getId()) || Objects.isNull(status)) {
            throw new LeadNewsException(AppHttpCodeEnum.PARAM_INVALID);
        }

        //查询认证信息是否存在
        ApUserRealName userRealName = this.getById(authDto.getId());
        if (Objects.isNull(userRealName)) {
            throw new LeadNewsException(AppHttpCodeEnum.NOT_FOUND_AUTH_INFO);
        }

        //查询审核信息提交人是否存在
        ApUser apUser = apUserMapper.selectById(userRealName.getUserId());
        if (Objects.isNull(apUser)) {
            throw new LeadNewsException(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }

        //判断是否重复审核
        if (userRealName.getStatus().equals(status)) {
            throw new LeadNewsException(AppHttpCodeEnum.NOT_DOUBLE_REVIEW);
        }

        //修改审核信息
        ApUserRealName apUserRealName = new ApUserRealName();
        apUserRealName.setId(authDto.getId());
        apUserRealName.setStatus(status);
        apUserRealName.setUpdatedTime(new Date());
        if (StringUtils.isNotBlank(authDto.getMsg())) {
            apUserRealName.setReason(authDto.getMsg());
        }
        this.updateById(apUserRealName);

        //判断审核通过与否  通过创建自媒体人 及 作者  并修改app用户的标识
        if (UserConstants.PASS_AUTH.equals(status)) {
            this.createWmUserAndApAuthor(apUser);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    private void createWmUserAndApAuthor(ApUser apUser) {

        //1.创建自媒体人
        //1.1 查询自媒体人信息   判断是否重复创建
        WmUser wmUser = weMediaClient.findByName(apUser.getName());
        if (Objects.nonNull(wmUser)) {
            throw new LeadNewsException(AppHttpCodeEnum.WE_MEDIA_PEOPLE_EXISTENCE);
        }

        //1.2 调用feign接口创建自媒体人
        WmUser user = new WmUser();
        user.setApUserId(apUser.getId());
        user.setName(apUser.getName());
        user.setPassword(apUser.getPassword());
        user.setImage(apUser.getImage());
        user.setPhone(apUser.getPhone());
        user.setStatus(UserConstants.STATUS_ENABLE);
        user.setType(UserConstants.ACCOUNT_NUMBER_TYPE_PERSONAL);
        user.setCreatedTime(new Date());
        weMediaClient.save(user);

        //2. 创建作者
        //2.1 查询作者
        ApAuthor author = articleClient.findByUserId(apUser.getId());
        if (Objects.nonNull(author)) {
            throw new LeadNewsException(AppHttpCodeEnum.AUTHOR_EXISTENCE);
        }

        //2.2 调用feign接口创建作者
        ApAuthor apAuthor = new ApAuthor();
        apAuthor.setName(apUser.getName());
        apAuthor.setType(UserConstants.AUTHOR_TYPE_MEDIA);
        apAuthor.setUserId(apUser.getId());
        apAuthor.setCreatedTime(new Date());

        WmUser justCreateUser = weMediaClient.findByName(apUser.getName());
        apAuthor.setWmUserId(justCreateUser.getId());
        articleClient.save(apAuthor);

        //修改审批状态
        ApUser userForStatus = new ApUser();
        userForStatus.setId(apUser.getId());
        userForStatus.setFlag(UserConstants.APP_USER_FLAG_MEDIA);
        apUserMapper.updateById(userForStatus);
    }
}
